package com.lostreseditores.sabersai.dataaccess.dao;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;

import com.lostreseditores.sabersai.dataaccess.sessionFactory.HibernateSessionFactory;
import com.lostreseditores.sabersai.model.Calificacion;
import com.lostreseditores.sabersai.model.VSalones;


public class CalificacionDAO implements ICalificacionDAO {
    private static final Log log = LogFactory.getLog(CalificacionDAO.class);

    // property constants
    //public static final Integer  CALIESTADON = "caliestadon";
    public static final String CALIESTADON = "caliestadon";

    //public static final Date  CALIFECHAD = "califechad";
    public static final String CALIFECHAD = "califechad";

    //public static final Integer  CALIIDN = "caliidn";
    public static final String CALIIDN = "caliidn";

    //public static final Integer  CALIPREMARCAN = "calipremarcan";
    public static final String CALIPREMARCAN = "calipremarcan";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
    *
    * @param Instance
    *            Calificacion Instance to persist
    * @throws RuntimeException
    *             when the operation fails
    */
    public void save(Calificacion instance) {
        log.debug("saving Calificacion instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
    public void savePaquete(Calificacion instance) {
        log.debug("saving Calificacion instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
    public void saveSalon(Calificacion instance) {
        log.debug("saving Calificacion instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
    * @param Instance
    *            Calificacion Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(Calificacion instance) {
        log.debug("deleting Calificacion instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public void deletePaquete(Calificacion instance) {
        log.debug("deleting Calificacion instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    /**
    *
    * @param Instance
    *            Calificacion Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(Calificacion instance) {
        log.debug("updating Calificacion instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }


    public Calificacion findById(Integer id) {
        log.debug("finding Calificacion instance with id: " + id);

        try {
            Calificacion instance = (Calificacion) getSession()
                                                       .get(Calificacion.class,
                    id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding Calificacion failed", re);
            throw re;
        }
    }

    public List<Calificacion> findByExample(Calificacion instance) {
        log.debug("finding Calificacion instance by example");

        try {
            List results = getSession().createCriteria("Calificacion")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  Calificacion entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< Calificacion> found by query
        */
    public List<Calificacion> findByProperty(String propertyName, Object value) {
        log.debug("finding Calificacion instance with property: " +
            propertyName + ", value: " + value);

        try {
            String queryString = "from Calificacion as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<Calificacion> findByCaliestadon(Object caliestadon) {
        return findByProperty(CALIESTADON, caliestadon);
    }

    public List<Calificacion> findByCalifechad(Object califechad) {
        return findByProperty(CALIFECHAD, califechad);
    }

    public List<Calificacion> findByCaliidn(Object caliidn) {
        return findByProperty(CALIIDN, caliidn);
    }

    public List<Calificacion> findByCalipremarcan(Object calipremarcan) {
        return findByProperty(CALIPREMARCAN, calipremarcan);
    }

    /**
    * Find all Calificacion entities.
    *
    * @return List<Calificacion> all Calificacion instances
    */
    public List<Calificacion> findAll() {
        log.debug("finding all Calificacion instances");

        try {
            String queryString = "from Calificacion";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<Calificacion> findByCriteria(String whereCondition) {
        log.debug("finding Calificacion " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from Calificacion model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<Calificacion> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in Calificacion failed", re);
            throw re;
        }
    }

    public List<Calificacion> findPageCalificacion(String sortColumnName,
        boolean sortAscending, int startRow, int maxResults) {
        log.debug("finding Calificacion findPageCalificacion");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from Calificacion model order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from Calificacion model";

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberCalificacion() {
        log.debug("finding Calificacion count");

        try {
            String queryString = "select count(*) from Calificacion model";
            Query queryObject = getSession().createQuery(queryString);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }
    	
	public List<Calificacion> findGruposColegios(Long coleidn) {
		log.debug("finding all Calificacion instances");

		try {

			String queryString = "from Calificacion where coleidn=" + coleidn
					+ "order by califechad desc";
			Query queryObject = getSession().createQuery(queryString);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List<Calificacion> findSalonesGrupo(Integer cal_caliidn) {
		log.debug("finding all Calificacion instances");

		try {

			String queryString = "from Calificacion where cal_caliidn="
					+ cal_caliidn + "order by califechad desc";
			Query queryObject = getSession().createQuery(queryString);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List<Calificacion> findCalificaciones(Integer cal_caliidn) {
		log.debug("finding all Calificacion instances");

		try {

			String queryString = "from Calificacion where cal_caliidn=" + cal_caliidn
					+ "order by califechad desc";
			Query queryObject = getSession().createQuery(queryString);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<Calificacion> findFechaGruposColegio(Long coleidn) {
		log.debug("finding all Calificacion instances");
        try {
            String queryString = "select extract(year from califechad) as fecha from Calificacion where coleidn="+coleidn + " group by extract(year from califechad)";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }
		
	public List<VSalones> findNumAlumnSalon(Integer caliidn) {
		log.debug("finding all VSalonesId instances");

		try {

			String queryString = "from VSalones where cal_caliidn=" + caliidn;
			Query queryObject = getSession().createQuery(queryString);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	
	// --------------------------------CONSULTAS PARA REPORTES FINALES
	// NUEVOS--------------------------------//

	public List findEstudiantesxCalificacion(Integer caliidn) {
		try {

			String queryString = "select * from (select avg(tblpuntaje) as puntaje, es.estunombrev, es.estuidn, ce.calipreorden, tblcurso_numero, es.estucodigov from f_consulta_promedioxmateria('"
					+ caliidn
					+ "') cc inner join(calificacionxestudiante ce inner join estudiante es on ce.estuidn = es.estuidn)on cc.tblcalixestuidn = ce.calixestuidn inner join(asignaturaxexamen ae inner join asignatura ag on ae.asigidn = ag.asigidn)on cc.tblasigxexamidn = ae.asigxexamidn and ag.clasasigidn = 1 group by es.estunombrev, es.estuidn, ce.calipreorden, tblcurso_numero order by puntaje desc) a where a.puntaje > 0.00";

			List<Object[]> queryObject = (List<Object[]>) getSession()
					.createSQLQuery(queryString).list();

			for (Object[] objects : queryObject) {
				BigDecimal puntaje = (BigDecimal) objects[0];
				String nombre = (String) objects[1];
				System.out.println(puntaje + nombre);
			}

		

			return queryObject;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findNotasxEstudiante(Integer caliidn, Integer estuidn) {
		try {

			String queryString = "SELECT tblasigxexamidn, tblcalixestuidn, tblpuntaje, ag.asigidn,ae.examidn, ae.asigxexamordn, ag.clasasigidn FROM f_consulta_promedioxmateria('"
					+ caliidn
					+ "') cc inner join asignaturaxexamen ae on cc.tblasigxexamidn = ae.asigxexamidn inner join asignatura ag on ae.asigidn = ag.asigidn inner join (calificacionxestudiante ce inner join estudiante es on ce.estuidn = es.estuidn)on cc.tblcalixestuidn = ce.calixestuidn where es.estuidn = "
					+ estuidn + " order by ag.clasasigidn,ag.asigidn";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
}
